<?php

namespace Frieza\Modules\Position\Actions;

use Admin\Service\ArticleService;
use Doraemon\cache\Queue;
use Doraemon\model\AdmOperateLog;
use Doraemon\model\AdmUserType;
use Doraemon\service\MemberRoleTag;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Doraemon\model\Member;
use Doraemon\service\admin\UserOperate;
use Doraemon\service\Article;
use Doraemon\service\Visitor;
use Doraemon\model\VendorseMent;

class Approve extends RowAction
{
    public $name = '认证';
    const USER_TYPE = [
        Member::AUTH_USER_V => '个人V认证',
        Member::AUTH_ORG_V => '机构V认证',
    ];
    const EDIT_TYPE = [
        Member::AUTH_USER_V,
        Member::AUTH_ORG_V
    ];

    public function handle($uid,Request $request)
    {
        $user_type = $request->get('user_type');
        $endorsement = $request->get('endorsement');
        $params = [
            'type' => (int)$user_type,
            'endorsement' => $endorsement,
        ];
        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;
        try {
            UserOperate::UserAuth($uid, $user_type, $admin_id, $params);
            // 如果认证的身份为机构V认证，则删除用户已发布过的整屋
            if ((int)$user_type === Member::AUTH_ORG_V) {
                Article::AdmDelArticlesByUid($uid);
            }
            $vid = Visitor::getVidByUid($uid);
            Queue::insertQueue('queue/UserRole/SaveRoleTag', array(
                'vid' => $vid,//vid
                'tag_id' => MemberRoleTag::ROLE_TAG_IDENTITY,//分群id
                'value' => '2',//对应的值
                'uid' => $uid,
            ), Queue::QUEUE_ROLE_TAG);

        }catch (\Exception $e) {
            return $this->response()->error('出错啦,稍后重试!!'.$e->getMessage());
        }
        AdmOperateLog::addLog($uid,AdmOperateLog::$operate_type['user_auth'],$admin_id,$admin_name);
        return $this->response()->success('操作成功')->refresh();
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function form($request)
    {
        $uid = $request->uid;
        //获取该用户的用户身份
        $member_info = Member::getUser($uid);
        $type = $member_info['type'];
        $user_type = in_array($type,self::EDIT_TYPE) ? $type : 0;
        //获取该用户的背书文案
        $endorsement_info = VendorseMent::getInfo($uid);
        $endorsement = '';
        if ($endorsement_info){
            $endorsement = $endorsement_info['endorsement'];
        }
        $this->select('user_type', '请选择身份类型')->options(self::USER_TYPE)->default($user_type);
        $this->text('endorsement', 'V背书文案')->rules()->default($endorsement);
    }
}
